using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Musicman.Business;
using Musicman.Common.Entities;
using System.IO;

namespace MusicmanWeb.USER
{
    public partial class EditProfile : MusicmanPage
    {
        protected override void Page_Load(object sender, EventArgs e)
        {
            ReddirectNonActiveSession();
            if (!IsPostBack)
            {
                Musicman.Common.Entities.User user = UserManager.Instance.GetUser(Int64.Parse(User.Identity.Name), true);
                BindUserInfo(user);
                BindUserStats(user.UserStats);
            }
        }

        private void BindUserInfo(Musicman.Common.Entities.User user)
        {
            EmailaddressTxt.Text = user.Emailaddress;
            FirstnameTxt.Text = user.Firstname;
            LastNameTxt.Text = user.Lastname;
            PersonSex.Text = user.PersonSex == Sex.Male ? "M" : "F";
            MailRequestCB.Checked = user.MailRequest;
        }

        private void BindUserStats(UserStats stats)
        {
            LastLoggedLbl.Text = stats.LastLoggedDate.ToString("dd-MM-yyyy");
            WebLogsLbl.Text = stats.TotalLogsWeb.ToString();
            ClientLogsLbl.Text = stats.TotalLogsCient.ToString();
            TotalFilesLbl.Text = stats.TotalFilesDownloaded.ToString();
            if (stats.TotalFilesLength > 1073741824)
            {
                TotalTrafficLbl.Text = Musicman.Common.Utilities.Converter.LengthGB(stats.TotalFilesLength);
            }
            else
            {
                TotalTrafficLbl.Text = Musicman.Common.Utilities.Converter.LengthMB(stats.TotalFilesLength);
            }
        }

        protected void Update_Button(object sender, CommandEventArgs e)
        {
            Musicman.Common.Entities.User user = UserManager.Instance.GetUser(Int64.Parse(User.Identity.Name));            
            bool changePass = changePasswordCb.Checked;
            OldPasswordTxt.Enabled = changePass;
            NewPasswordTxt.Enabled = changePass;
            NewPassword2Txt.Enabled = changePass;
            OldPasswordTxt.Attributes.Add("value", OldPasswordTxt.Text);
            NewPasswordTxt.Attributes.Add("value", NewPasswordTxt.Text);
            NewPassword2Txt.Attributes.Add("value", NewPassword2Txt.Text);

            bool valid = true;
            string validatioinErrors = "";
            int errCnt = 0;

            if (changePass)
            {
                valid = valid && Musicman.Common.Utilities.Converter.EncriptPassword(OldPasswordTxt.Text) == user.Password;
                if (!valid)
                {
                    errCnt++;
                    validatioinErrors += String.Format("{0}. Old password incorrect <br/>", errCnt);
                }
                valid = !String.IsNullOrEmpty(NewPasswordTxt.Text);
                if (!valid)
                {
                    errCnt++;
                    validatioinErrors += String.Format("{0}. Password can't be empty <br/>", errCnt);
                }
                valid = NewPasswordTxt.Text == NewPassword2Txt.Text;
                if (!valid)
                {
                    errCnt++;
                    validatioinErrors += String.Format("{0}. New paswword and old password mismatch <br/>", errCnt);
                }
                valid = errCnt == 0;
            }

            bool changePicture = profilePictureUpload.FileName != "";
            string pictureErrors = "";
            if (changePicture)
            {
                string fileName = profilePictureUpload.FileName.ToLower();
                if (!(fileName.EndsWith(".jpg") || fileName.EndsWith(".jpeg") || fileName.EndsWith(".gif")))
                {
                    errCnt++;
                    pictureErrors += String.Format("{0}. Picture must be jpg or gif <br/>", errCnt);
                }
                if (profilePictureUpload.FileContent.Length > 1048576)
                {
                    errCnt++;
                    pictureErrors += String.Format("{0}. Size of the picture is limited to 1 MB <br/>", errCnt);
                }
                valid = errCnt == 0;
            }

            if (!valid)
            {
                ValidationMessage.Text = validatioinErrors;
                ValidationMessage.Visible = true;
                PictureValidationErrors.Text = pictureErrors;
                PictureValidationErrors.Visible = true;
                return;
            }

            user.Firstname = FirstnameTxt.Text;
            user.Lastname = LastNameTxt.Text;
            user.MailRequest = MailRequestCB.Checked;
            user.PersonSex = PersonSex.Text == "M" ? Sex.Male : Sex.Female;
            if (changePass)
            {
                user.Password = Musicman.Common.Utilities.Converter.EncriptPassword(NewPasswordTxt.Text);
            }
            if (!UserManager.Instance.UpdateUserProfile(user))
            {
                ValidationMessage.Text = "Error updating user";
                ValidationMessage.Visible = true;
            }
            else
            {
                ValidationMessage.Text = "User profile updated sucessfully";
                ValidationMessage.Visible = true;
            }
            if (changePicture)
            {
                byte[] imageData = Musicman.Common.Utilities.Converter.CreateTumbnail(96, profilePictureUpload.FileContent);
                if (!UserManager.Instance.UpdateProfilePicture((long)user.Personid, imageData))
                {
                    PictureValidationErrors.Text = "Error updating profile picture";
                    PictureValidationErrors.Visible = true;
                }
                else
                {
                    PictureValidationErrors.Text = "Profile picture updated sucessfully";
                    PictureValidationErrors.Visible = true;
                }
            }
        }


    }
}
